package com.atguigu.mongodb;

import com.atguigu.mongodb.entity.User;
import com.atguigu.mongodb.repository.UserRepository;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.domain.*;

import java.util.List;

/**
 * @author fenge
 */
@SpringBootTest
public class DemomogoApplicationTests1 {
    @Autowired
    private UserRepository userRepository;

    @Test
    public void createUser(){
        User user = new User("vieew",24,true);
        User save = userRepository.save(user);
        System.out.println("save = " + save);
        //611c7ae2b1f4d253f68a6135
    }

    @Test
    public void list(){
        List<User> all = userRepository.findAll();
        for (User user : all) {
            System.out.println("user = " + user);
        }
    }

    @Test
    public void getById(){
        User user = userRepository.findById("611c7ae2b1f4d253f68a6135").get();
        System.out.println("user = " + user);
    }

    @Test
    public void findUserList(){
        User user = new User();
        user.setName("FengGe");
        user.setAge(18);
        Example<User> userExample = Example.of(user);
        List<User> userList = userRepository.findAll(userExample);
        System.out.println("userList = " + userList);
    }

    @Test
    public void findUsersLikeName(){
        ExampleMatcher matching = ExampleMatcher.matching()
                .withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING)
                .withIgnoreCase(true);
        User user = new User();
        user.setName("u");
        Example<User> userExample = Example.of(user, matching);
        List<User> userList = userRepository.findAll(userExample);
        for (User user1 : userList) {
            System.out.println("user1 = " + user1);
        }
    }

    @Test
    public void findUserPage(){
        Sort sort = Sort.by(Sort.Direction.DESC, "age");
        Pageable request = PageRequest.of(0, 1, sort);
        ExampleMatcher exampleMatcher = ExampleMatcher.matching()
                .withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING)
                .withIgnoreCase(true);
        User user = new User();
        user.setName("u");
        Example<User> userExample = Example.of(user, exampleMatcher);
        Page<User> pages = userRepository.findAll(userExample, request);
        List<User> content = pages.getContent();
        for (User user1 : content) {
            System.out.println("user1 = " + user1);
        }
        System.out.println("pages = " + pages);
    }

    @Test
    public void updateUser(){
        User user = userRepository.findById("611c7ae2b1f4d253f68a6135").get();
        user.setAge(9999);
        user.setName("vieeu");
        User save = userRepository.save(user);
        System.out.println("save = " + save);
    }
}
